package cn.ming.leo.resource;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;

import cn.ming.leo.bean.Box;
import cn.ming.leo.bean.Door;
import cn.ming.leo.bean.DoorTools;
import cn.ming.leo.bean.Tools;
import cn.ming.leo.bean.User;
import cn.ming.leo.bean.WechatInfo;
import cn.ming.leo.bean.vo.RedisProductBean;
import cn.ming.leo.service.DoorToolsService;
import cn.ming.leo.utils.TimeFormat;

@RestController
@RequestMapping("/wechat")
public class WechatResource {
	static Log log = Log.getLog(WechatResource.class);
	private final static String APPID = "wx749e46db4a0e497b";
	private final static String SECRET = "dd4a52b2886097b1eb1bd60a92cb4674";

	@Autowired
	DoorToolsService doorToolsService;

	@RequestMapping(value = "/regist")
	public String regist(HttpServletRequest request,
			HttpServletResponse response) {
		int subscribe = 0;
		// 用户同意授权，获取code
		String code = request.getParameter("code");
		log.info("code  is {}" + code);
		if (code == null) {
			return "code is null";
		} else {
			// 通过code换取网页授权access_token
			SnsAccessToken snsAccessToken = SnsAccessTokenApi
					.getSnsAccessToken(APPID, SECRET, code);
			// String json=snsAccessToken.getJson();
			String token = snsAccessToken.getAccessToken();
			String openId = snsAccessToken.getOpenid();
			// 拉取用户信息(需scope为 snsapi_userinfo)
			ApiResult apiResult = SnsApi.getUserInfo(token, openId);

			log.warn("getUserInfo:" + apiResult.getJson());
			if (apiResult.isSucceed()) {
				JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
				String nickName = jsonObject.getString("nickname");
				// 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				int sex = jsonObject.getIntValue("sex");
				String city = jsonObject.getString("city");// 城市
				String province = jsonObject.getString("province");// 省份
				String country = jsonObject.getString("country");// 国家
				String headimgurl = jsonObject.getString("headimgurl");
				// String unionid = jsonObject.getString("unionid");
				// 获取用户信息判断是否关注
				ApiResult userInfo = UserApi.getUserInfo(openId);
				log.warn(JsonKit.toJson("is subsribe>>" + userInfo));
				if (userInfo.isSucceed()) {
					String userStr = userInfo.toString();
					subscribe = JSON.parseObject(userStr).getIntValue(
							"subscribe");
				}

				WechatInfo wechatInfo = WechatInfo.find.where()
						.eq("open_id", openId).findUnique();
				if (wechatInfo == null) {

					wechatInfo = new WechatInfo();
					wechatInfo.setCity(city);
					wechatInfo.setCountry(country);
					wechatInfo.setProvince(province);
					wechatInfo.setCreateTime(TimeFormat.nowTime());
					wechatInfo.setUpdateTime(new Date());
					wechatInfo.setOpenId(openId);
					wechatInfo.setSex("" + sex);
					wechatInfo.setSubscribe("" + subscribe);
					wechatInfo.setHeadUrl(headimgurl);
					wechatInfo.setNickname(nickName);
					wechatInfo.save();
				} else {
					wechatInfo.setCity(city);
					wechatInfo.setCountry(country);
					wechatInfo.setProvince(province);
					wechatInfo.setUpdateTime(new Date());
					wechatInfo.setOpenId(openId);
					wechatInfo.setSex("" + sex);
					wechatInfo.setSubscribe("" + subscribe);
					wechatInfo.setHeadUrl(headimgurl);
					wechatInfo.setNickname(nickName);
					wechatInfo.update();
				}
			}

			User user = User.find.where().eq("open_id", openId).findUnique();
			if (user == null) {
				return "redirect:reg.html?id=" + openId;
			} else {
				return "redirect:tools.html?userId=" + user.getId();
			}
		}
	}

	@RequestMapping(value = "/oauth")
	public String oauth(HttpServletRequest request, HttpServletResponse response) {
		// 用户同意授权，获取code
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		log.info("code  is {}" + code);
		log.info("state  is {}" + state);

		if (code == null) {
			return "code is null";
		} else {
			// 通过code换取网页授权access_token
			SnsAccessToken snsAccessToken = SnsAccessTokenApi
					.getSnsAccessToken(APPID, SECRET, code);
			String openId = snsAccessToken.getOpenid();
			User user = User.find.where().eq("open_id", openId).findUnique();
			if (user == null) {
				// 注册
				return "redirect:reg.html?id=" + openId;
			} else {
				/**
				 * 领取
				 */
				if ("draw".equals(state)) {
					List<DoorTools> list = DoorTools.find.where()
							.eq("status", 1).eq("put_user_id", user.getId())
							.findList();
					if (list.size() == 0) {
						return "您没有待领取的工具";
					} else {
						int type = 1;

						if (list.size() > 1) {
							type = 2;
						}
						DoorTools doorTools = list.get(0);
						Door door = Door.find.byId("" + doorTools.getDoorId());
						Box box = Box.find.byId("" + door.getBoxId());
						RedisProductBean redisProductBean = new RedisProductBean(
								door.getBoxId(), doorTools.getDoorId(), 1,
								type, user.getId());
						doorToolsService.productDoors(box.getBoxNo(),
								redisProductBean);

						doorTools.setUpdateTime(new Date());
						doorTools.setTakeUserId(user.getId());
						doorTools.setTakeTime(TimeFormat.nowTime());
						doorTools.setStatus(2);
						doorTools.update();
						Tools tools = Tools.find.byId(""
								+ doorTools.getToolsId());
						tools.setToolsStatus(2);
						tools.setUpdateTime(new Date());
						tools.update();
						return "您的主柜编号为：" + box.getBoxNo() + ",格子编号为:"
								+ door.getDoorNo() + "已打开。请取走您的工具";

					}
				} else if ("return".equals(state)) {
					List<DoorTools> list = DoorTools.find.where()
							.eq("status", 2).eq("put_user_id", user.getId())
							.findList();
					if (list.size() == 0) {
						return "您没有需要待归还的工具";
					} else {
						int type = 3;
						if (list.size() > 1) {
							type = 4;
						}
						DoorTools doorTools = list.get(0);
						Door door = Door.find.byId("" + doorTools.getDoorId());
						Box box = Box.find.byId("" + door.getBoxId());
						RedisProductBean redisProductBean = new RedisProductBean(
								door.getBoxId(), doorTools.getDoorId(), 2,
								type, user.getId());
						doorToolsService.productDoors(box.getBoxNo(),
								redisProductBean);

						doorTools.setUpdateTime(new Date());
						doorTools.setTakeUserId(user.getId());
						doorTools.setReturnTime(TimeFormat.nowTime());
						doorTools.setStatus(4);
						doorTools.update();
						Tools tools = Tools.find.byId(""
								+ doorTools.getToolsId());
						tools.setToolsStatus(4);
						tools.setUpdateTime(new Date());
						tools.update();
						return "您的主柜编号为：" + box.getBoxNo() + ",格子编号为:"
								+ door.getDoorNo() + "已打开。请归还你的工具，谢谢。";
					}
				}
			}
		}
		return "";
	}

}
